package net.keebook.webapp.ws;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import net.keebook.webapp.dao.KeeBookDao;
import net.keebook.webapp.dao.PasswordDao;
import net.keebook.webapp.entity.PasswordItem;
import net.keebook.webapp.model.SessionModel;
import net.keebook.webapp.util.AccessRight;

import org.json.JSONException;
import org.json.JSONObject;

@Path("/setfavored")
@Stateless
public class SetFavoredService {
	@Inject
	private PasswordDao passwordDao;
	@Inject
	private KeeBookDao keeBookDao;
	
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public String saveSettings(@Context HttpServletRequest request, String jsonString) throws JSONException {
		HttpSession session = request.getSession(true);
		SessionModel sessionModel = SessionModel.getInstance(session);
		
		JSONObject json = new JSONObject(jsonString);
		
		JSONObject result = new JSONObject();
		if (!sessionModel.getLoggedIn()) {
			result.put("success", false);
		} else {
			PasswordItem item = getPasswordDao().get(json.getString("id"));
			if (item != null && getPasswordDao().canAccess(sessionModel.getUserId(), item.getId()) && getKeeBookDao().canAccess(sessionModel.getUserId(), item.getKeeBook().getId(), AccessRight.READ_WRITE)) {
				item.setFavored(json.getBoolean("favored"));
				getPasswordDao().update(item);
				result.put("success", true);
			} else {
				result.put("success", false);
			}
		}
		return result.toString();
	}

	public PasswordDao getPasswordDao() {
		return passwordDao;
	}

	public void setPasswordDao(PasswordDao passwordDao) {
		this.passwordDao = passwordDao;
	}

	public KeeBookDao getKeeBookDao() {
		return keeBookDao;
	}

	public void setKeeBookDao(KeeBookDao keeBookDao) {
		this.keeBookDao = keeBookDao;
	}
}
